// HandlerBodyManager
package core

import (
	"code.google.com/p/goprotobuf/proto"
	"fmt"
)

import "GoNet/pb"

type HandlerBodyManager struct {
	HandlerMap map[int32]func(msg *Message)
	BodyMap    map[int32]func() interface{}
}

func NewHandlerBodyManager() *HandlerBodyManager {
	return &HandlerBodyManager{make(map[int32]func(msg *Message)), make(map[int32]func() interface{})}
}

//添加handler
func (manager *HandlerBodyManager) AddHandler(msgId int32, handFunction func(msg *Message), newBody func() interface{}) {
	manager.HandlerMap[int32(msgId)] = handFunction
	manager.BodyMap[int32(msgId)] = newBody
}

func (manager *HandlerBodyManager) Init() {
	manager.AddHandler(55, login, func() interface{} { return new(pb.TestPb) })
}

func login(msg *Message) {
	body := msg.Body.(*pb.TestPb)
	fmt.Println(body.GetInts())
	fmt.Println(body.GetLongs())
	fmt.Println(body.GetStr())

	cg := new(pb.TestPb)
	cg.Str = proto.String("这个是返回的")
	cg.Ints = proto.Int32(51)
	cg.Longs = proto.Int64(414)

	nMsg := new(Message)
	nMsg.Body = cg
	nMsg.Type = 52
	msg.Session.writeMsg(nMsg)

}

//获得handler
func (manager *HandlerBodyManager) GetHandler(msgId *int32) func(msg *Message) {
	handler, has := manager.HandlerMap[*msgId]
	if has {
		return handler

	}
	return nil
}

//获得消息体
func (manager *HandlerBodyManager) GetBody(msgId *int32) interface{} {
	body, has := manager.BodyMap[*msgId]
	if has {
		return body()
	}
	return nil
}
